import { IReduxMarketItem, IReduxMarketInfo } from "../interface";
import { HUOBI_SUBSCRIBE_MARKET_SYMBOLS_PREFIX } from "./constants";

/**
 * 
 * @param marketInfo market 数据，从 Redux 中获取
 * @param coinType 币种
 * @param split 是否要把币种分开，传入 BTC/ETH, split = true 时，返回 ETH； 否则返回 原值
 */
export function utilGetMarketInfoByCoinType(marketInfo: IReduxMarketInfo, coinType: string, split?: boolean) : Array<IReduxMarketItem> {
    let {market} = marketInfo;
    if (!market.length) {
        return [];
    }
    if (coinType === 'all') {
        return market;
    }
    const res = market.filter((value) => {
        const v = value.type.split('/')[0];
        return v == coinType;
    });
    return res;
}

/**
 * trans btcusdt -> BTC/USDT
 * @param coinType 
 */
export function utilTransferCoinTypeToUpperCase (coinType: string) {
    for (let i = 0 ; i < HUOBI_SUBSCRIBE_MARKET_SYMBOLS_PREFIX.length; i++) {
        let prefix = HUOBI_SUBSCRIBE_MARKET_SYMBOLS_PREFIX[i];
        if (coinType.indexOf(prefix) === 0) {
            let len = prefix.length;
            let t1 = prefix.toUpperCase();
            let t2 = coinType.slice(len).toLocaleUpperCase();
            return t1 + '/' + t2;
        }
    }
    return null;
}

export function utilGetLastPrice(marketInfo: IReduxMarketInfo, coinType: string): number {
    let market = marketInfo.market;
    let index = market.findIndex(v => v.type == coinType);
    if (index > -1) {
        return market[index].lastPrice || 0;
    }
    return 0;
}


/**
 * 
 * @param marketInfo 
 * @param coinType 'BTC/ETH' | 'BTC'
 * @param amountTo 
 */
export function utilGetAmountToByCoinType(marketInfo: IReduxMarketInfo, coinType: string, amountTo?: 'cny' | 'd'): number {
    let {market, amountToCNY = 6.8} = marketInfo;
    if (coinType.indexOf('/') > 0) {
        coinType = coinType.split('/')[0];
    }
    coinType = `${coinType}/USDT`;
    let index = market.findIndex(v => v.type == coinType);
    if (index > -1) {
        if (amountTo === 'd') {
            return Number(market[index].value.toFixed(4));
        }
        // console.log('marketIndex...', market[index].value, coinType, amountToCNY);
        return Number((market[index].value * amountToCNY).toFixed(4));
    }
    return 0;
}